package cn.yuan.arithmetic.sort;

/**
 * 直接插入排序实现.
 *
 * @author : yjs
 * @date: 2020-12-17 10:25
 */
public class DirectInsertSort {

    public static void main(String[] args) {
        int[] array = {3,4,7,4,1,9,13,24,11,45,22,45};
        System.out.println(print(array));
        DirectInsertSort.sort(array);
        System.out.println(print(array));
    }

    /**
     * 实现
     *
     */
    public static void sort(int[] array) {
       // 直接插入排序
        for (int i = 1; i < array.length; i++) {
            // 待插入元素
            int temp = array[i];
            int j;
            for (j = i - 1; j >= 0; j--) {
                // 将大于temp的往后移动一位
                if (array[j] > temp) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            array[j + 1] = temp;
        }
    }

    /**
     * 打印
     *
     */
    private static String print(int[] array){
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
